package com.jyl.sort;

import java.util.Arrays;

/**
 * @ClassName QuickSort
 * @Author admin
 * @Date 2024/6/16
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] nums = {56, 80, 52,52, 49, 31, 57, 93, 27, 9, 55};
        System.out.println(partition(nums, 0, nums.length - 1));
        System.out.println(Arrays.toString(nums));

        // ...
        sort(nums);
        System.out.println(Arrays.toString(nums));

    }

    public static void sort(int[] nums) {
        sort(nums, 0, nums.length - 1);
    }

    /**
     * 时间复杂度：最优 O(nlogn) 最差(n²)
     *空间复杂度：最优 O(logn) 最差O(n)
     */
    public static void sort(int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }
        int pivotIndex = partition(nums, start, end);
        sort(nums, start, pivotIndex - 1);
        sort(nums, pivotIndex + 1, end);
    }

    // O(n)
    private static int partition(int[] nums, int start, int end) {
        int pivot = nums[start];
        int low = start;
        int high = end;

        while (low < high) {
            while (nums[high] >= pivot && high > low) {
                high--;
            }
            nums[low] = nums[high];

            while (nums[low] <= pivot && low < high) {
                low++;
            }
            nums[high] = nums[low];
        }
        nums[low] = pivot;

        return low;
    }

}
